import { v4 as uuidv4 } from 'uuid';
import { invoke } from '@tauri-apps/api/core';

export function uuid(): string {
    return uuidv4();
}

export function uuidTrim(): string {
    return uuidv4().replaceAll('-', '');
}

export function setLocalStorage(key: string, value: string) {
    localStorage.setItem(key, value);
}

export function getLocalStorage(key: string): string | null {
    let value = localStorage.getItem(key);
    return value;
}

export const clearLocalStorage = (key: string | undefined) => {
    if (key === undefined) {
        return localStorage.clear();
    } else {
        return localStorage.removeItem(key);
    }
};

export function getLocalStorageWithDefault(key: string, defaultValue?: string): string {
    let value = localStorage.getItem(key);
    if (value != null) {
        return value;
    }
    if (value === null && defaultValue) {
        return defaultValue
    }
    return '';
}

export function getLocalStorageObjectWithDefault<T>(key: string, defaultValue: T): T {
    let v = getLocalStorage(key);
    if (!v) {
        return defaultValue;
    }
    try {
        let obj = JSON.parse(v);
        return obj;
    } catch (err) {
        console.error(err);
    }
    return defaultValue;
}

export async function homePath(): Promise<string> {
    const path: string = await invoke('plugin:mg-platform|home_path');
    return path;
}

export const logout = () => {
    clearLocalStorage('g01_token');
};
export const isLogin = (): boolean => {
    let token = getLocalStorage('g01_token');
    if (token) {
        return true;
    }
    //从缓存中获取到
    return false;
};

export const setToken = (token: string) => {
    setLocalStorage('g01_token', token);
};

export const getToken = (): string | null => {
    let token = getLocalStorage('g01_token');
    if (token) {
        return token;
    }
    //从缓存中获取到
    return null;
};
